package com.whfc.common.weixin.mp;

import com.whfc.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/11/7 14:09
 */
public class OAuth2Api {

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";

    private static final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";

    private static final String AUTH_URL = "https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}";

    private static final String USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}";

    private static Logger logger = LoggerFactory.getLogger(OAuth2Api.class);

    /**
     * 用户code换取accessToken
     *
     * @param appId
     * @param secret
     * @param code
     * @return
     */
    public static String accessToken(String appId, String secret, String code) {
        String url = MessageFormat.format(ACCESS_TOKEN_URL, appId, secret, code);
        String response = HttpUtil.doGet(url);
        logger.info("oauth获取accessToken,url:{},response:{}", url, response);
        return response;
    }

    /**
     * 刷新accessToken
     *
     * @param appId
     * @param refreshToken
     * @return
     */
    public static String refreshAccessToken(String appId, String refreshToken) {
        String url = MessageFormat.format(REFRESH_TOKEN_URL, appId, refreshToken);
        String response = HttpUtil.doGet(url);
        logger.info("oauth刷新accessToken,url:{},response:{}", url, response);
        return response;
    }

    /**
     * 验证accessToken
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static String auth(String accessToken, String openId) {
        String url = MessageFormat.format(AUTH_URL, accessToken, openId);
        String response = HttpUtil.doGet(url);
        logger.info("oauth验证accessToken,url:{},response:{}", url, response);
        return response;
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static String userInfo(String accessToken, String openId) {
        String url = MessageFormat.format(USERINFO_URL, accessToken, openId);
        String response = HttpUtil.doGet(url);
        logger.info("oauth获取用户信息,url:{},response:{}", url, response);
        return response;
    }
}
